<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>简单实现 call、apply、 bind | Jayken (谢小舜)|谢小舜的个人博客</title>
    <meta name="description" content=" Jayken（谢小舜）的个人主页，记录我的程序员职业成长之路，分享前端、Java踩过的坑！">
    
    
    <link rel="preload" href="/assets/css/0.styles.0c98b5d4.css" as="style"><link rel="preload" href="/assets/js/app.2d175a42.js" as="script"><link rel="preload" href="/assets/js/2.af4947b8.js" as="script"><link rel="preload" href="/assets/js/11.c26367e4.js" as="script"><link rel="prefetch" href="/assets/js/10.ead388bb.js"><link rel="prefetch" href="/assets/js/12.e15eef2b.js"><link rel="prefetch" href="/assets/js/13.71248d26.js"><link rel="prefetch" href="/assets/js/14.caa891a6.js"><link rel="prefetch" href="/assets/js/15.dba29244.js"><link rel="prefetch" href="/assets/js/3.8c0cb32d.js"><link rel="prefetch" href="/assets/js/4.ea6b297e.js"><link rel="prefetch" href="/assets/js/5.e528d392.js"><link rel="prefetch" href="/assets/js/6.d3c0fe75.js"><link rel="prefetch" href="/assets/js/7.f9e4b783.js"><link rel="prefetch" href="/assets/js/8.cfbdc4b7.js"><link rel="prefetch" href="/assets/js/9.e68d7ec2.js">
    <link rel="stylesheet" href="/assets/css/0.styles.0c98b5d4.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar"><header class="navbar"><div class="navbar-wrap"><div><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/images/logo_z.gif" alt="Jayken (谢小舜)|谢小舜的个人博客" class="logo"> <!----></a> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link">首页</a></div><div class="nav-item"><a href="/post/" class="nav-link router-link-active">博客</a></div><div class="nav-item"><a href="https://github.com/jaykenxie" target="_blank" rel="noopener noreferrer" class="nav-link external">
  GitHub
  <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></div> <!----></nav></div> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div></div></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link">首页</a></div><div class="nav-item"><a href="/post/" class="nav-link router-link-active">博客</a></div><div class="nav-item"><a href="https://github.com/jaykenxie" target="_blank" rel="noopener noreferrer" class="nav-link external">
  GitHub
  <svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg></a></div> <!----></nav>  <!----> </aside> <main class="page"><div class="page-left"><div class="page-content"><div class="page-title"><h3>简单实现 call、apply、 bind</h3> <div class="page-title_info"><span class="page-title_author"><img src="https://avatars3.githubusercontent.com/u/29194135?v=4" alt class="page-title_avatar"> <span>谢小舜</span></span> <span class="page-title_time"><span>2019-07-10 07:28:13</span></span></div></div> <div class="theme-content content__default"><h2 id="call-apply"><a href="#call-apply" aria-hidden="true" class="header-anchor">#</a> call(),apply()</h2> <p>call() 方法调用一个函数, 其具有一个指定的this值和分别地提供的参数(参数的列表)。
</p> <blockquote><p>call和apply只是接收参数上的不同</p></blockquote> <h2 id="用法-mdn"><a href="#用法-mdn" aria-hidden="true" class="header-anchor">#</a> 用法(MDN)</h2> <blockquote><p>fun.call(thisArg, arg1, arg2, ...)</p></blockquote> <h3 id="thisarg"><a href="#thisarg" aria-hidden="true" class="header-anchor">#</a> thisArg</h3> <p>在fun函数运行时指定的this值。需要注意的是，指定的this值并不一定是该函数执行时真正的this值，如果这个函数处于non-strict mode，则指定为null和undefined的this值会自动指向全局对象(浏览器中就是window对象)，同时值为原始值(数字，字符串，布尔值)的this会指向该原始值的自动包装对象。</p> <h3 id="arg1-arg2"><a href="#arg1-arg2" aria-hidden="true" class="header-anchor">#</a> arg1, arg2, ...</h3> <p>指定的参数列表。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> reply <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token keyword">this</span><span class="token punctuation">.</span>animal<span class="token punctuation">,</span> <span class="token string">'typically sleep between'</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>sleepDuration<span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">' '</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>reply<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span>
  animal<span class="token punctuation">:</span> <span class="token string">'cats'</span><span class="token punctuation">,</span> sleepDuration<span class="token punctuation">:</span> <span class="token string">'12 and 16 hours'</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token function">greet</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// cats typically sleep between 12 and 16 hours</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p>上面例子中当用call调用greet方法的时候，该方法的this值会绑定到obj对象。
我们来分析下call做了哪些事情：</p> <ol><li>greet函数执行了；</li> <li>greet执行上下文中的this被改成了obj</li></ol> <p>下面我们来动手实现一下：</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span>
  name<span class="token punctuation">:</span> <span class="token string">'111'</span><span class="token punctuation">,</span>
  <span class="token function-variable function">fn</span><span class="token punctuation">:</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>name<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
<span class="token comment">// 我们知道fn中的this 就是调用它的obj</span>
obj<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span>


<span class="token comment">// 在Function原型上添加我们的方法</span>
<span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">myCall</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">ctx<span class="token punctuation">,</span> <span class="token operator">...</span>args</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token comment">//这里用Symbol以免覆盖了属性</span>
  <span class="token keyword">const</span> key <span class="token operator">=</span> <span class="token function">Symbol</span><span class="token punctuation">(</span><span class="token string">'fn'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">/**
   * call的第一个参数如果为null和undefined时this值会自动指向全局对象(浏览器中就是window对象)，
   * 同时值为原始值(数字，字符串，布尔值)的this会指向该原始值的自动包装对象，原生的call会用Object包装一下。
   */</span>
  ctx <span class="token operator">=</span> ctx <span class="token operator">?</span> <span class="token function">Object</span><span class="token punctuation">(</span>ctx<span class="token punctuation">)</span> <span class="token punctuation">:</span> window<span class="token punctuation">;</span>
  <span class="token comment">/**
   * 这里的this就指向调用的调用call的函数，上例中就是greet
   * 所以我们在实现的时候只要将call的第一个参数挂到greet中的某一个属性中去就可以了
   */</span>
  ctx<span class="token punctuation">[</span>key<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>
  <span class="token comment">// 这里调用并将参数传给 this函数</span>
  <span class="token keyword">const</span> result <span class="token operator">=</span> ctx<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token comment">// 调用完成后将刚刚挂在的属性删除</span>
  <span class="token keyword">delete</span> ctx<span class="token punctuation">[</span>key<span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> result<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
<span class="token comment">// 测试一下</span>
greet<span class="token punctuation">.</span><span class="token function">myCall</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// cats typically sleep between 12 and 16 hours</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br></div></div><h1 id="bind"><a href="#bind" aria-hidden="true" class="header-anchor">#</a> bind()</h1> <p>bind和call的区别是call会被立即调用执行，而bind则返回的是一个改变了执行上下文的函数。</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">function</span> <span class="token function">greet</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">var</span> reply <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token keyword">this</span><span class="token punctuation">.</span>animal<span class="token punctuation">,</span> <span class="token string">'typically sleep between'</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>sleepDuration<span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">' '</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>reply<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>

<span class="token keyword">var</span> obj <span class="token operator">=</span> <span class="token punctuation">{</span>
  animal<span class="token punctuation">:</span> <span class="token string">'cats'</span><span class="token punctuation">,</span> sleepDuration<span class="token punctuation">:</span> <span class="token string">'12 and 16 hours'</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>

<span class="token function">greet</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>  <span class="token comment">// cats typically sleep between 12 and 16 hours</span>
<span class="token function">greet</span><span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">// cats typically sleep between 12 and 16 hours</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br></div></div><p>我们用call来实现</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token class-name">Function</span><span class="token punctuation">.</span>prototype<span class="token punctuation">.</span><span class="token function-variable function">myBind</span> <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token parameter">ctx<span class="token punctuation">,</span> <span class="token operator">...</span>args</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
  <span class="token keyword">const</span> self <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>
  <span class="token comment">// 返回一个函数</span>
  <span class="token keyword">return</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
   <span class="token comment">// 用call去调用并返回结果</span>
    <span class="token keyword">return</span> <span class="token function">self</span><span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>ctx<span class="token punctuation">,</span> <span class="token operator">...</span>args<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div></div> <div class="page-foot"><span><a href="/post/#JS">#JS</a></span></div></div> <div class="page-comment"><!----></div> <!----> </div> <div class="page-right"><div class="toc"><h4>目录</h4> <ul class="toc-wrap"><!----> <ul><li><a href="#call-apply">call(),apply()</a></li></ul> <!----> <!----><!----> <ul><li><a href="#用法-mdn">用法(MDN)</a></li></ul> <!----> <!----><!----> <!----> <ul><ul><li><a href="#thisarg">thisArg</a></li></ul></ul> <!----><!----> <!----> <ul><ul><li><a href="#arg1-arg2">arg1, arg2, ...</a></li></ul></ul> <!----></ul></div></div></main> <footer class="footer" data-v-437632ea><div class="footer-ctx" data-v-437632ea><div class="footer-ctx-l" data-v-437632ea><h5 data-v-437632ea>自述</h5> <p data-v-437632ea>接触前端以来一直想自己设计开发一个博客，用于分想和记录工作、生活和学习中遇到的问题，与解决问题的思路和感悟。 (^o^)/~。</p></div> <div class="footer-ctx-m" data-v-437632ea><h5 data-v-437632ea>相关链接</h5> <ul class="flink" data-v-437632ea><li class="flink-wrap" data-v-437632ea><a href="/" class="dedline" data-v-437632ea>关于我</a></li><li class="flink-wrap" data-v-437632ea><a href="https://github.com/jaykenxie" class="dedline" data-v-437632ea>GitHub</a></li><li class="flink-wrap" data-v-437632ea><a href="https://weibo.com/autoshun" class="dedline" data-v-437632ea>微博</a></li></ul></div> <div class="footer-ctx-r" data-v-437632ea><img src="/images/logo_w.png" alt="Jayken (谢小舜)|谢小舜的个人博客" class="footer-ctx-r_logo" data-v-437632ea></div></div> <div class="footer-info" data-v-437632ea><a href="/" data-v-437632ea>©Jayken</a> <i data-v-437632ea> · </i> <a href="https://v1.vuepress.vuejs.org" data-v-437632ea>Vuepress</a>
      |  
    <a href="http://www.miitbeian.gov.cn/publish/query/indexFirst.action" target="_blank" class="dedline" data-v-437632ea>粤ICP备18012800号-2</a></div></footer></div><div class="global-ui"></div></div>
    <script src="/assets/js/app.2d175a42.js" defer></script><script src="/assets/js/2.af4947b8.js" defer></script><script src="/assets/js/11.c26367e4.js" defer></script>
  </body>
</html>
